import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Spin, Select, message, Steps } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import HOCSelect from '@/components/AntDesign/Select';

const { Option } = Select;
const FormItem = Form.Item;
const { Step } = Steps;

@connect(({ loading, addemp, addinfo }) => ({
  loading: loading.models.addemp || false,
  addemp,
  addinfo,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      contSerType: 1,
      suppId: null, // 签约方Id
      custId: null, // 客户Id
      suppContId: null, // 供应商合同Id      
    };
  }

  componentDidMount() {
    // 获取当前角色所在公司对应的平台供应商
    const {
      dispatch,
      form,
      addinfo: { isGoBack = false },
      addinfo,
    } = this.props;

    if (!isGoBack) {
      dispatch({
        type: 'addemp/updateModelData',
        payload: {
          isSameComy: true,
        },
      });
      dispatch({
        type: 'addemp/updateQuoQuery',
        payload: {
          suppId: undefined, // 签约方id
          custId: undefined, // 客户名称id
          contId: undefined, // 商务合同id
          quoId: undefined, // 报价单id
        },
      });
      dispatch({
        type: 'addemp/updateModelData',
        payload: {
          supplyList: [], // 签约方
          customerNameList: [], // 签约方为本地，客户名称
          contList: [], // 商务合同列表
          quoList: [], // 报价单列表
          supplyContList: [], // 供应商合同列表
        },
      });
      dispatch({
        type: 'addemp/plasuppList',
        payload: {},
        callback: response => {
          if (response.success && response.data) {
            dispatch({
              type: 'addemp/updateModelData',
              payload: { suppReplaceCorpId: response.data[0].suppId },
            });
            // 签约方(供应商)列表
            dispatch({
              type: 'addemp/contractParty',
              payload: { name: null, status: 2 },
              callback: r => {
                if (r.success && r.data) {
                  dispatch({
                    type: 'addemp/updateModelData',
                    payload: { supplyList: r.data },
                  });

                  for (let index = 0; index < r.data.length; index += 1) {
                    const item = r.data[index];
                    if (response.data[0].suppId === item.suppId) {
                      form.setFieldsValue({ suppId: item.suppId });
                      this.setState({
                        suppId: item.suppId,
                      });
                      this.getCustomers(item.suppId);
                      break;
                    }
                  }
                } else {
                  message.warning(`${r.message || '暂无数据！'}`);
                }
              },
            });
          }
        },
      });
    } else {
      this.setState({
        contSerType: addinfo.contSerType,
      });
    }
    dispatch({
      type: 'addinfo/updateModelData',
      payload: {
        isGoBack: false,
      },
    });
  }

  // 签约方选择 : 根据选择显示不同
  selectCompany = suppId => {
    const { form, dispatch, addemp } = this.props;
    form.resetFields(['custId', 'contId', 'quoId']);
    dispatch({
      type: 'addemp/updateQuoQuery',
      payload: {
        suppId,
        contId: undefined,
        custId: undefined,
        quoId: undefined,
      },
    });
    dispatch({
      type: 'addemp/updateModelData',
      payload: {
        isSameComy: suppId === addemp.suppReplaceCorpId,
        customerNameList: [],
        supplyContList: [],
        contList: [],
        quoList: [],
      },
    });
    if (suppId === addemp.suppReplaceCorpId) {
      this.getCustomers(suppId); // 本地  请求客户名称
    } else {
      this.getSupplyers(suppId); // 全国 请求供应商合同
    }
    this.setState({ suppId });
  };

  // 选择签约方为本地：请求客户名称
  getCustomers = suppId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addemp/customerList',
      payload: { suppId },
      callback: response => {
        if (response.success && response.data.length) {
          dispatch({
            type: 'addemp/updateModelData',
            payload: { customerNameList: response.data },
          });
        } else {
          message.warning('该签约方下暂无客户！');
        }
      },
    });
  };

  // 选择客户名称：请求商务合同
  selectCustomers = custId => {
    const { dispatch, form } = this.props;
    form.resetFields(['contId', 'quoId']);
    this.setState({ custId });
    dispatch({
      type: 'addemp/updateQuoQuery',
      payload: {
        contId: undefined, // 商务合同id
        quoId: undefined, // 报价单id
      },
    });
    dispatch({
      type: 'addemp/updateModelData',
      payload: { supplyContList: [], custId, contList: [], quoList: [] },
    });
    dispatch({
      type: 'addemp/getBusiness',
      payload: { custId, queryType: 3 },
      callback: response => {
        if (response.success && response.data.length) {
          dispatch({
            type: 'addemp/updateModelData',
            payload: { contList: response.data },
          });
        } else {
          message.warning('该客户名称下暂无商务合同！');
        }
      },
    });
  };

  // 选择商务合同：请求报价单
  selectCont = (custContId, options) => {
    const { dispatch, form } = this.props;
    const { suppId, custId } = this.state;
    if (options.props.state === 3) {
      message.warning('该商务合同已到期！');
    }
    form.resetFields(['quoId']);
    dispatch({
      type: 'addemp/updateQuoQuery',
      payload: { quoId: undefined },
    });
    dispatch({
      type: 'addemp/updateModelData',
      payload: { quoList: [] },
    });
    const pamList = {
      custContId,
      suppId,
      custId,
    };
    dispatch({
      type: 'addemp/getQuotation',
      payload: pamList,
      callback: response => {
        if (response.success && response.data.length) {
          dispatch({
            type: 'addemp/updateModelData',
            payload: { quoList: response.data },
          });
        } else {
          message.warning('该商务合同下无报价单！');
        }
      },
    });
  };

  // 选择报价单
  selectQuo = (id, p) => {
    this.setState({
      contSerType: p.props.sertype,
    });
  };

  // 根据签约方为全国：请求供应商合同
  getSupplyers = suppId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'addemp/getNameList',
      payload: { suppId, queryType: 3 },
      callback: response => {
        if (response.success && response.data.length) {
          dispatch({
            type: 'addemp/updateModelData',
            payload: { supplyContList: response.data },
          });
        } else {
          message.warning('暂无供应商合同列表');
        }
      },
    });
  };

  // 根据选择的供应商合同：请求客户名称
  selectSupply = (contId, options) => {
    const { dispatch, form } = this.props;
    if (options.props.state === 3) {
      message.warning('该供应商合同已到期！');
    }
    form.resetFields(['custId', 'quoId']);
    this.setState({ suppContId: contId });
    dispatch({
      type: 'addemp/updateQuoQuery',
      payload: {
        custId: undefined, // 客户名称id
        quoId: undefined, // 报价单id
      },
    });
    dispatch({
      type: 'addemp/updateModelData',
      payload: { customerNameList: [], quoList: [] },
    });
    dispatch({
      type: 'addemp/getCustnameList',
      payload: { contId },
      callback: response => {
        if (response.success && response.data.length) {
          dispatch({
            type: 'addemp/updateModelData',
            payload: { customerNameList: response.data },
          });
        } else {
          message.warning('该供应商合同下无客户！');
        }
      },
    });
  };

  // 选择客户名称：请求报价单
  selectSuppCust = custId => {
    const { dispatch, form } = this.props;
    const { suppContId } = this.state;
    form.resetFields(['quoId']);
    dispatch({
      type: 'addemp/updateQuoQuery',
      payload: { quoId: undefined },
    });
    dispatch({
      type: 'addemp/updateModelData',
      payload: { quoList: [] },
    });
    dispatch({
      type: 'addemp/pleaseQun',
      payload: { custId, custContId: suppContId },
      callback: response => {
        if (response.success && response.data && response.data.length) {
          dispatch({
            type: 'addemp/updateModelData',
            payload: { quoList: response.data },
          });
        } else {
          message.warning('该客户名称下无报价单！');
        }
      },
    });
  };

  // 下一步
  nextStep = () => {
    const { contSerType } = this.state;
    const { dispatch, form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const temp = values;
        Object.keys(values).forEach(key => {
          if (values[key] && values[key].key) {
            temp[key] = values[key].key;
          } else {
            temp[key] = values[key] ? values[key] : '';
          }
        });

        const addEmpSeleInfo = { ...values, contSerType };
        dispatch({
          type: 'addemp/updateQuoQuery',
          payload: { ...values },
        });
        window.localStorage.setItem('addEmpSeleInfo', JSON.stringify({ ...addEmpSeleInfo }));
        router.push('/customservicemanage/addemployee/addinfo');

        const state = {
          formRedux: {
            requestAddBaseDto: { formReduxRequestPdInfo: [] },
            requestInsAndAccuDto: {},
            empLaborContDto: {},
          },
          // 上一步骤信息：
          suppId: null,
          contId: null,
          custId: null,
          quoId: null,
          contSerType: '1', // 合同类型
          quoInfo: {}, // 报价单所有信息
          quoPdList: [], // 报价单产品列表

          requestAddBaseDto: {
            idType: '1', // 身份证
            nation: '156', // 中国
            // 收费信息数据
            requestPdInfo: [], // 产品分项设置数据源
          },
          costCenterList: [], // 成本中心列表
          isHasIns: false, // 有无社保
          isHasAccu: false, // 有无公积金
          insUnifyFlag: 1, // 五险合不合一 :1合2不合
          pdSetFlag: '2', // 产品分项设置
          isAssSetFlag: '2', // 社保险种分项设置
          isSupplyRun: false, // 是否由供应商执行

          requestInsAndAccuDto: {
            // 社保公积金信息
          },
          insList: [], // 社保险种
          insKinds: [], // 险种id列表：获取社保账户需要传参
          isSerConfig: false, // 是否使用服务配置
          isInsWageSet: false, // 是否社保工资分项
          isInsIde: false, // 是否有缴费人员类别
          insPayStyleList: [], // 社保缴费方式列表
          insPayStyle: null, // 社保缴费方式
          accuPayStyleList: [], // 公积金缴费方式列表
          accuPayStyle: null, // 公积金缴费方式
          isInsPayStyleSingle: false, // 社保缴费方式是不是单立户
          isAccuPayStyleSingle: false, // 公积金缴费方式是不是单立户
          insAcountList: [], // 社保账户
          insGroupList: [], // 社保组合
          accuAcountList: [], // 公积金账户
          accuGroupList: [], // 公积金组合
          serConfigList: [], // 服务配置列表
          isHasInjury: false, // 有无工伤险
          isSecAccu: false, // 是否维护工伤二级户
          secAccuList: [], // 工伤二级户
          insIdeList: [], // 缴费人员类别列表
          serConfigData: [], // 服务配置数据源

          empLaborContDto: {
            // 合同信息
          },
          isDisableCont: false, // 是否可修改信息
          isContEndRequired: false, // 合同结束日期
          isTryDateRequired: true, // 有无试用期
          sendBeginDate: null, // 业务开始年月 获取合同用
          submitData: {}, // 提交时的数据
        };
        dispatch({
          type: 'addinfo/updateModelData',
          payload: { ...state },
        });
      }
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      addemp: {
        addempQuery,
        isSameComy,
        supplyList,
        customerNameList, // 签约方为本地，客户名称
        contList,
        quoList,
        supplyContList,
      },
      loading,
    } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const SelelctCust = () => {
      if (isSameComy) {
        return (
          <div>
            <FormItem {...formItemLayout} label="客户名称">
              {getFieldDecorator('custId', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: addempQuery.custId,
              })(
                <HOCSelect
                  placeholder="请选择"
                  onSelect={this.selectCustomers}
                  showSearch
                  optionFilterProp="children"
                >
                  {customerNameList.map(one => (
                    <Option key={one.custId} value={one.custId} title={one.name}>
                      {one.name}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="商务合同">
              {getFieldDecorator('contId', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: addempQuery.contId,
              })(
                <HOCSelect
                  placeholder="请选择"
                  onSelect={(value, options) => this.selectCont(value, options)}
                  showSearch
                  optionFilterProp="children"
                >
                  {contList.map(one => (
                    <Option key={one.contId} value={one.contId} state={one.contState} title={one.contName}>
                      {one.contName}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="报价单">
              {getFieldDecorator('quoId', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: addempQuery.quoId,
              })(
                <HOCSelect
                  placeholder="请选择"
                  onSelect={this.selectQuo}
                  showSearch
                  optionFilterProp="children"
                >
                  {quoList.map(one => (
                    <Option key={one.quoId} value={one.quoId} sertype={one.serType} title={one.quoName}>
                      {one.quoName}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </div>
        );
      }
      return (
        <div>
          <FormItem {...formItemLayout} label="供应商合同">
            {getFieldDecorator('contId', {
              rules: [{ required: true, message: '请选择' }],
              initialValue: addempQuery.contId,
            })(
              <HOCSelect
                placeholder="请选择"
                onSelect={(value, options) => this.selectSupply(value, options)}
                showSearch
                optionFilterProp="children"
              >
                {supplyContList.map(one => (
                  <Option key={one.contId} value={one.contId} state={one.contState}>
                    {one.contName}
                  </Option>
                ))}
              </HOCSelect>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="客户名称">
            {getFieldDecorator('custId', {
              rules: [{ required: true, message: '请选择' }],
              initialValue: addempQuery.custId,
            })(
              <HOCSelect
                placeholder="请选择"
                onSelect={this.selectSuppCust}
                showSearch
                optionFilterProp="children"
              >
                {customerNameList.map(one => (
                  <Option key={one.custId} value={one.custId} title={one.name}>
                    {one.name}
                  </Option>
                ))}
              </HOCSelect>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="报价单">
            {getFieldDecorator('quoId', {
              rules: [{ required: true, message: '请选择' }],
              initialValue: addempQuery.quoId,
            })(
              <HOCSelect
                placeholder="请选择"
                onSelect={this.selectQuo}
                showSearch
                optionFilterProp="children"
              >
                {quoList.map(one => (
                  <Option key={one.quoId} value={one.quoId} sertype={one.serType}>
                    {one.quoName}
                  </Option>
                ))}
              </HOCSelect>
            )}
          </FormItem>
        </div>
      );
    };
    return (
      <Form>
        <PageHeaderWrapper>
          <Spin tip="Loading..." spinning={loading}>
            <Card>
              <Steps current={0} style={{ marginBottom: 70 }}>
                <Step title="选择报价单" />
                <Step title="填写基本信息" />
                <Step title="完成" />
              </Steps>
              <FormItem {...formItemLayout} label="签约方">
                {getFieldDecorator('suppId', {
                  rules: [{ required: true, message: '请选择' }],
                  initialValue: addempQuery.suppId,
                })(
                  <HOCSelect
                    placeholder="请选择"
                    onSelect={this.selectCompany}
                    showSearch
                    optionFilterProp="children"
                  >
                    {supplyList.map(one => (
                      <Option key={one.suppId} value={one.suppId}>
                        {one.name}
                      </Option>
                    ))}
                  </HOCSelect>
                )}
              </FormItem>
              <SelelctCust />
              <div style={{ marginTop: '100px', marginBottom: '30px', textAlign: 'center' }}>
                <Button
                  style={{ marginRight: '30px' }}
                  size="large"
                  onClick={() => router.push('/customservicemanage/addemployee/index')}
                >
                  上一步
                </Button>
                <Button size="large" type="primary" onClick={this.nextStep}>
                  下一步
                </Button>
              </div>
            </Card>
          </Spin>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
